package com.zzzs.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 *
 * ForkJoin 工作窃取，分而治之
 * @author zhu_shuai
 * @since 2021/6/28
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long startNum;
    private Long endNum;

    public ForkJoinDemo(Long startNum, Long endNum) {
        this.startNum = startNum;
        this.endNum = endNum;
    }

    @Override
    protected Long compute() {
        long diff = 10000L;
        if ((endNum-startNum) < diff) {
            long sum = 0;
            for (long i = startNum; i < endNum; i++) {
                sum += i;
            }
            return sum;
        }else {
            long average = (startNum + endNum)/2;
            ForkJoinDemo task1 = new ForkJoinDemo(startNum, average);
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(average, endNum);
            task2.fork();
            return task1.join() + task2.join();
        }
    }
}
